package com.chinazyjr.framework.web.iterceptors;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chinazyjr.framework.web.accessControl.RequestRateLimitManager;

public class RequestRateLimitInteceptor extends HandlerInterceptorAdapter {

	private static final Logger LOGGER = LoggerFactory.getLogger("LOGGER.WEB_API_REQUEST");

	private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");
	
	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链 如果返回true
	 * 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		startTimeThreadLocal.set(System.currentTimeMillis());
		String validateStr = request.getParameter("phoneNum");
		if (StringUtils.isNotBlank(validateStr)) {
			try {
				if (!RequestRateLimitManager.asynPush(validateStr)) {
					JSONObject object = new JSONObject();
					object.put("code", "500");
					object.put("msg", "请求频率过快,请稍后再试");
					response.setCharacterEncoding("UTF-8");
					response.setContentType("text/html; charset=UTF-8");
					response.getWriter().write(object.toJSONString());
					LOGGER.info("request inteceptor refuse mobile:{}",validateStr);
					return false;
				}
			} catch (Exception e) {
				LOGGER.error("error",e);
			}
		}
		return true;
	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作 可在modelAndView中加入数据，比如当前时间
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
	 * 
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Long start = startTimeThreadLocal.get();
		Long now = System.currentTimeMillis();
		String uri = request.getRequestURI();
		String method = request.getMethod();
		@SuppressWarnings("unchecked")
		Map<String, String[]> params = request.getParameterMap();
		// WriteMapNullValue序列化 区分 "" 和null
		String paramString = JSON.toJSONString(params, SerializerFeature.WriteMapNullValue);
		LOGGER.info("HttpServletRequest:{}|method:{}|{}ms|params:{}", uri,method,now-start, paramString);
	}

}
